﻿using CommonLib.Attr;
using CommonLib.Base;
using CommonLib.CodeEntity;
using CommonLib.Util;
using System.Text.RegularExpressions;

namespace CommonLib.Lexer;

[Order(1)]
public class InsertLexer : BaseLexer
{
    public override bool Check()
        => Txt.StartsWith("INSERT ");

    protected override BaseCodeEntity Run()
    {
        var entity = new InsertCodeEntity();
        var txt = Real.TrimEnd(';');
        if (txt.Contains("VALUES ") || txt.Contains("VALUES("))
        {
            var pre = Regex.Match(txt, "(.*)VALUES(\\s|\\()").Result("$1").Trim();
            entity.Head = pre;
            var values = Regex.Match(txt, "VALUES(.*)").Result("$1").Trim();
            if (values.StartsWith('(') && values.EndsWith(')')) values = values[1..^1];
            ListParams(values, entity.Values);
        }
        else
        {
            var pre = Regex.Match(txt, "(.*?)SELECT").Result("$1").Trim();
            var sel = Regex.Match(txt, "SELECT.*").Value.Trim();
            entity.Head = pre;
            entity.Values.Add(SqlFactory.Create(sel).Execute());
        }
        return entity;
    }
}